package permission

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminrole"
	"private-domain-overseas-service/tools/ent/adminrouter"
	"private-domain-overseas-service/tools/ent/predicate"
	"strconv"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminRouterPagesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminRouterPagesLogic - 后台页面查询接口
func NewAdminRouterPagesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminRouterPagesLogic {
	return &AdminRouterPagesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminRouterPagesLogic) AdminRouterPages(req *types.GetAllPagesRequest) (resp []string, err error) {
	adminRouterDAO := permission.NewAdminRouterDao(l.ctx, l.svcCtx)
	adminRoleDAO := permission.NewAdminRoleDao(l.ctx, l.svcCtx)

	// 路由
	var adminRouters []*ent.AdminRouter
	// 查菜单的条件
	conditions := make([]predicate.AdminRouter, 0)
	conditions = append(conditions, adminrouter.AdminRouterStatusEQ(bizadmin.StatusEnabled))
	conditions = append(conditions, adminrouter.AdminRouterHideInMenuEQ(bizadmin.NotHide))
	conditions = append(conditions, adminrouter.AdminRouterMenuTypeEQ(bizadmin.TypeMenu))

	if req.RoleId != 0 {
		// 根据id查询角色
		roleConditions := make([]predicate.AdminRole, 0, 1)
		roleConditions = append(roleConditions, adminrole.IDEQ(int(req.RoleId)))
		roles, err := adminRoleDAO.AdminRoleConditionsAll(roleConditions)
		if err != nil {
			return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询角色失败: %v", err.Error()))
		}

		// 从角色中获取路由id
		ids := strings.Split(roles[0].AdminRoleRouterIds, ",")
		routerIds := lo.Map(ids, func(item string, index int) int {
			id, _ := strconv.Atoi(item)
			return id
		})

		// 查询路由
		conditions = append(conditions, adminrouter.IDIn(routerIds...))
		adminRouters, _, err = adminRouterDAO.AdminRouterConditionsAll(conditions)
		if err != nil {
			return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询路由失败: %v", err.Error()))
		}
	} else {
		var listErr error
		// 查所有路由页面
		adminRouters, _, listErr = adminRouterDAO.AdminRouterConditionsAll(conditions)
		if listErr != nil {
			return nil, listErr
		}
	}

	// 取出路由名称
	pages := lo.Map(adminRouters, func(item *ent.AdminRouter, index int) string {
		return item.AdminRouterRouteName
	})

	// 返回路由名称数组
	return pages, nil
}
